package com.likai.blog.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.likai.blog.dao.IBlogMapper;
import com.likai.blog.lucene.BlogIndex;
import com.likai.blog.pojo.Blog;
import com.likai.blog.service.IBlogService;
import com.likai.blog.utils.IdUtil;

@Service("blogService")
public class BlogServiceImpl implements IBlogService {
	
	@Autowired
	private IBlogMapper blogMapper ;
	
	private BlogIndex blogIndex = new BlogIndex() ;

	@Transactional(readOnly=true)
	public List<Blog> findListGroupDate() {
		return blogMapper.selectListGroupDate();
	}

	@Transactional(readOnly=true)
	public List<Blog> findList(Blog po) {
		return blogMapper.selectList(po) ;
	}

	@Transactional
	public Blog findByBlogId(String blogId) {
		Blog blog = blogMapper.selectByBlogId(blogId) ;
		blogMapper.updateByClickHit(blogId) ;
		return blog;
	}

	@Transactional
	public int updateInfo(Blog po) {
		boolean flag = false ;
		String blogId = po.getBlogId() ;
		if(blogId == null || "".equals(blogId)) {
			po.setBlogId(IdUtil.uuid());
			po.setClickHit(0);
			po.setReplyHit(0);
			po.setReleaseDate(new Date());
			if(blogMapper.insertInfo(po) == 1) {
				//写入索引
				try {
					blogIndex.addIndex(po);
				} catch (Exception e) {
					e.printStackTrace();
				}
				flag = true ;
			} 
		} else {
			if(blogMapper.updateByKey(po) == 1) {
				try {
					blogIndex.updateIndex(po);
				} catch (Exception e) {
					e.printStackTrace();
				}
				flag = true ;
			}
		}
		
		if(flag) {
			return 1 ;
		} else {
			return 0 ;
		}
	}

	@Transactional(readOnly=true)
	public Blog findLastInfo(Blog po) {
		return blogMapper.selectLastInfo(po) ;
	}

	@Transactional(readOnly=true)
	public Blog findNextInfo(Blog po) {
		return blogMapper.selectNextInfo(po) ;
	}

	@Transactional
	public int deleteByKey(String [] ids) {
		boolean flag = false ;
		for (String id : ids) {
			if(blogMapper.deleteByKey(id) == 1) {
				flag = true ;
				//删除索引
				try {
					blogIndex.deleteIndex(id);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				flag = false ;
				//编程式手动回滚
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		}
		if(flag) {
			return 1 ;
		} else {
			return 0 ;
		}
	}

}
